$(function() {
    //taskTable2 = SwiftUI.swiftTable.getInstance(opts2);
    var thiswinurl = window.location.href,
        operateStr = "operateStatus",
        operateIdx = thiswinurl.indexOf(operateStr),
        taskNoStr = "taskNo",
        taskNoIdx = thiswinurl.indexOf(taskNoStr),
        operateStatus = (operateIdx == -1) ? "" : thiswinurl.substring(operateIdx + (operateStr.length + 1), taskNoIdx - 1),
        taskNoVal = (taskNoIdx == -1) ? "" : thiswinurl.substring(taskNoIdx + (taskNoStr.length + 1));

    $.ajax({
        type: "post",
        dataType: "json",
        data: {
            "taskNo": taskNoVal
        },
        url: DI.queryRegionTaskDetail,
        success: function(data) {
            if (data.retFlag == 1) {
                mainCtrl.taskNo = taskNoVal;
                mainCtrl.categoryNameTxt = data.data.categoryName;
                mainCtrl.startTime = data.data.startTime;
                mainCtrl.endTime = data.data.endTime;
                mainCtrl.taskTopic = data.data.taskTopic;
                mainCtrl.taskStatus = data.data.taskStatus;
                mainCtrl.percent = data.data.percent;
                mainCtrl.compltPercent = data.data.compltPercent;
                mainCtrl.totalNum = data.data.totalNum;
                mainCtrl.compltNum = data.data.compltNum;
                mainCtrl.operateStatus = operateStatus;
                popCtrl.operateStatus = operateStatus;
            } else {
                console.log("获取数据失败了哟>>>" + data.errorMessage)
            }
        },
        error: function(err) {
            console.log(err);
        }
    });

    var taskTable = null;
    var opts = {
        targetId: "taskTable",
        templateId: "tabletask",
        settings: {
            searchParam: {
                "taskNo": taskNoVal
            },
            url: DI.queryRegionTaskCommList,
            ajaxType: "json",
            sourceInterface: {
                INum: "total",
                IData: "rows"
            },
            paginationIndexName: {
                "peerpageRows": "pageLimit",
                "currentPage": "pageNo"
            }
        },
        customFuncs: {
            distributionInfo: function(commClassifyCode, compltNum) {
                $("#popup_distribution").show();
                $("#load-assign").show();
                popCtrl.assignList = [];
                popCtrl.searchcode = "";
                $(".search-code .err-box").hide();
                location.hash = "popup_distribution";
                popCtrl.alldestnum = compltNum;
                popCtrl.commClassifyCode = commClassifyCode;
                $.ajax({
                    type: "post",
                    dataType: "json",
                    data: {
                        "commClassifyCode": commClassifyCode,
                        "taskNo": mainCtrl.taskNo
                    },
                    url: DI.queryStoreDestNum,
                    success: function(data) {
                        $("#load-assign").hide();
                        if (data.retFlag == 1) {
                            popCtrl.assignList = data.data;
                            var total = 0;
                            for (var i = 0; i < popCtrl.assignList.length; i++) {
                                var iptVal = popCtrl.assignList[i].destNum == undefined ? 0 : popCtrl.assignList[i].destNum;
                                total += parseInt(iptVal == "" ? 0 : iptVal, 10);
                            }
                            popCtrl.curdestnum = total;
                        } else {
                            console.log("获取分配详情接口，返回数据错误")
                        }
                    },
                    error: function(err) {
                        $("#load-assign").hide();
                        console.log(err);
                    }
                });
            },
            checkNum: function() {
                $(this).removeClass("err-ipt").removeAttr("title");;
                var reg = /^[0-9]+$/;
                if (!reg.test($(this).val())) {
                    $(this).addClass("err-ipt").attr("title", "目标台数为数字");
                }
            }
        }
    };
    taskTable = SwiftUI.swiftTable.getInstance(opts);

    var mainCtrl = avalon.define({
        $id: "mainController",
        taskTopic: "",
        startTime: "",
        endTime: "",
        categoryList: [],
        taskNo: "",
        categoryNameTxt: "",
        percent: "",
        compltPercent: "",
        totalNum: "",
        compltNum: "",
        operateStatus: 0,
        isimpcomm: false,
        taskStatus: "",
        downloadURL: DI.storeAssignExport,
        importXls: function() {
            $("#popup_import").show();
            popCtrl.taskNo = mainCtrl.taskNo;
        },
        downloadtemp: function() {
            var isdownload = taskTable.table.$model.returnData.isShowDownloadBut;
            if (!isdownload) {
                PLATFORM.showTips("error", "不存在未分配商品，不能下载模板");
                return;
            }
            window.location.href = DI.storeAssignExport + "?taskNo=" + mainCtrl.taskNo;
        }

    });

    var popCtrl = avalon.define({
        $id: "popController",
        assignList: [],
        searchcode: "",
        delId: "",
        operateStatus: 0,
        commClassifyCode: "",
        taskNo: "",
        alldestnum: 0,
        curdestnum: 0,
        uploadFile: function() {
            if ($("#upladFile").val() == "") {
                return;
            }
            $("#load-import").show();
            $("#form_file").ajaxSubmit({
                type: "post",
                dataType: "json",
                url: DI.storeAssignImport,
                success: function(data) {
                    $("#load-import").hide();
                    if (data.retFlag == 1) {
                        $("#popup_import").hide();
                        taskTable.searchParam.pageNo = "1";
                        taskTable.refresh();
                        PLATFORM.showTips("success", "导入成功");
                    } else {
                        PLATFORM.showTips("error", data.errorMessage);
                    }
                    $("#upladFile").after($("#upladFile").clone().val(""));
                    $("#upladFile").remove();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    console.log("ajax error");
                    console.log(XMLHttpRequest);
                }
            });
        },
        fastSearch: function() {
            var codeList = $("#popup_distribution tbody tr .region-code");
            $(".region-code.highlight").removeClass("highlight");
            $(".search-code .err-box").hide();
            if(popCtrl.searchcode.length != 4){
                $(".search-code .err-box").show();
                return;
            }
            var hashId = "";
            for (var i = 0; i < popCtrl.assignList.length; i++) {
                if (popCtrl.assignList[i].orgCode.indexOf(popCtrl.searchcode) != -1) {
                    $(codeList[i]).addClass("highlight");
                    if (hashId == "") {
                        hashId = "td_" + popCtrl.assignList[i].orgCode;
                    }
                }
            }
            location.hash = "";
            location.hash = hashId;
        },
        saveRegionComm: function() {
            if ($("#popup_distribution .u-ipt.err-ipt").length > 0) {
                return;
            }
            var commData = [];
            var iptList = $("#popup_distribution tbody .edit-ipt input");
            for (var i = 0; i < iptList.length; i++) {
                var commObj = {
                    "id": popCtrl.assignList[i].id,
                    "taskNo": popCtrl.assignList[i].taskNo,
                    "destNum": ($(iptList[i]).val() == "" ? 0 : $(iptList[i]).val()),
                    "orgCode": popCtrl.assignList[i].orgCode
                };
                commData.push(commObj);
            }
            var stringComm = JSON.stringify(commData);
            $.ajax({
                type: "post",
                dataType: "json",
                data: {
                    "commList": stringComm,
                    "commClassifyCode": popCtrl.commClassifyCode,
                    "taskNo": mainCtrl.taskNo
                },
                url: DI.upsertStoreDestNum,
                success: function(data) {
                    if (data.retFlag == 1) {
                        $("#popup_distribution").hide();
                        PLATFORM.showTips("success", "门店目标台数保存成功");
                    } else {
                        PLATFORM.showTips("error", data.errorMessage);
                    }
                },
                error: function(err) {
                    console.log(err);
                }
            });
        },
        delData: function() {
            $.ajax({
                type: "post",
                dataType: "json",
                data: {
                    "commClassifyCode": popCtrl.delId
                },
                url: DI.deleteComm,
                success: function(data) {
                    $("#popup_del").hide();
                    if (data.retFlag == 1) {
                        taskTable2.searchParam.pageNo = "1";
                        taskTable2.refresh();
                        PLATFORM.showTips("success", "删除主推商品成功");
                    } else {
                        PLATFORM.showTips("error", data.errorMessage);
                    }
                },
                error: function(err) {
                    console.log(err);
                }
            });
        },
        checkNum: function() {
            $(this).removeClass("err-ipt").removeAttr("title");
            if ($(this).val() == "") {
                var total = 0;
                var iptList = $("#popup_distribution tbody .edit-ipt input");
                for (var i = 0; i < iptList.length; i++) {
                    var iptVal = $(iptList[i]).val() == "" ? 0 : $(iptList[i]).val();
                    total += parseInt(iptVal, 10);
                }
                popCtrl.curdestnum = total;
                return;
            }
            var reg = /^[0-9]+$/;
            if (!reg.test($(this).val())) {
                $(this).addClass("err-ipt").attr("title", "目标台数为数字");
            } else {
                var total = 0;
                var iptList = $("#popup_distribution tbody .edit-ipt input");
                for (var i = 0; i < iptList.length; i++) {
                    var iptVal = $(iptList[i]).val() == "" ? 0 : $(iptList[i]).val();
                    total += parseInt(iptVal, 10);
                }
                popCtrl.curdestnum = total;
            }
        }
    });

    $(".u-tabs .tab").click(function() {
        var $this = $(this),
            parent = $this.parents(".u-tabs"),
            tabs = parent.find(".tab-box .tab"),
            cnts = parent.find(".cnt-box .cnt"),
            idx = tabs.index($this);

        tabs.removeClass("sel");
        $this.addClass("sel");
        cnts.hide();
        cnts.eq(idx).show();
    });
    PLATFORM.datepickerRange("#starttime", "#endtime");

    avalon.scan();
});
/*
 * firefox下回车事件不兼容问题
 * 
 */
function fastSearch(evt){
    evt = (evt) ? evt : ((window.event) ? window.event : "");  //兼容IE和Firefox获得keyBoardEvent对象
    var keyVal = evt.keyCode?evt.keyCode:evt.which;
    $(".search-code .u-ipt").val($(".search-code .u-ipt").val().replace(/\D/g,''));
    var searchCode = $(".search-code .u-ipt").val();
    if(keyVal == 13){
        var codeList = $("#popup_distribution tbody tr .region-code");
        $(".region-code.highlight").removeClass("highlight");
        $(".search-code .err-box").hide();
        if(searchCode.length != 4){
            $(".search-code .err-box").show();
            return;
        }
        var hashId = "";
        var tableList = $("#popup_distribution tbody tr"),
            tableLen = tableList.length;
        for (var i = 0; i < tableLen; i++) {
            var curCodeObj = $(tableList[i]).find(".region-code"),
                curCode = curCodeObj.text();
            console.log(curCode);
            if (curCode.indexOf(searchCode) != -1) {
                curCodeObj.find("span").addClass("highlight");
                if (hashId == "") {
                    hashId = "td_" + curCode;
                }
            }
        }
        location.hash = "";
        location.hash = hashId;
    }
}
/*
 * 分配状态  过滤器
 * 0未分配,1已分配;
 */
avalon.filters.filterTaskStatus = function(str, args, args2) {
    var ret = "";
    if (str == 0) {
        ret = ""
    } else if (str == 1) {
        ret = "√";
    }
    return ret;
}